﻿using Analyzor.entity;
using SOAFramework.Library;
using SOAFramework.Library.Html;
using SOAFramework.Library.Refile;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Analyzor
{
    public partial class frmStock : Form
    {
        HashSet<int> ingnoreSet = new HashSet<int>();
        public frmStock()
        {
            InitializeComponent();
        }

        private async void frmStock_Load(object sender, EventArgs e)
        {
            ingnoreSet.Add(134);
            ingnoreSet.Add(157);
            await Run();
            MessageBox.Show("over");
        }

        public async Task Run()
        {
            Parallel.For(19, 262, new ParallelOptions { MaxDegreeOfParallelism = 2 }, (i, loopstate) =>
            {
                if (ingnoreSet.Contains(i))
                {
                    return;
                }
                var url = $"https://tushare.pro/document/2?doc_id={i}";
                HttpClient client = new HttpClient();
                var response = client.GetAsync(url).Result;
                var html = response.Content.ReadAsStringAsync().Result;
                if (html.StartsWith("{"))
                {
                    return;
                }

                HtmlNode root = HtmlParser.Parse(html);
                List<Table> tables = root.GetTags<Table>();
                if (tables.Count == 0)
                {
                    return;
                }
                //接口处理
                HtmlNode divNode = tables[0].Node.ParentNode.Name.Equals("div") ? tables[0].Node.ParentNode : tables[0].Node.ParentNode.ParentNode;
                List<P> pList = divNode.GetTags<P>();
                List<H2> h2List = divNode.GetTags<H2>();
                string text = pList[0].text;
                string[] infoArr = text.Split('\r', '\n');
                List<string> infoList = new List<string>();
                foreach (var arr in infoArr)
                {
                    if (String.IsNullOrEmpty(arr))
                    {
                        continue;
                    }
                    infoList.Add(arr);
                }
                string name = h2List[0].text;
                string code = infoList[0];
                if (code.Contains("（上线中）"))
                {
                    return;
                }
                code = code.Split('：')[1];
                string description = infoList[1];
                string remark = "";
                string prompt = "";
                if (infoList.Count > 2)
                {
                    remark = infoList[2];
                }
                var data = DbContext.StockClient.Queryable<Interface>().First(t => t.Code.Equals(code));
                if (data == null)
                {
                    data = new Interface
                    {
                        Code = code,
                        Name = name,
                        Description = description,
                        Remark = remark,
                        Prompt = prompt,
                    };
                    data = DbContext.StockClient.Insertable(data).ExecuteReturnEntity();
                }
                //入参处理
                List<Parameter> innerList = GetParameterFromTable(GetTable(tables, "输入参数,接口参数"), 0);
                Save(innerList, 0, data.Id);
                //出参处理
                List<Parameter> outerList = GetParameterFromTable(GetTable(tables, "输出参数"), 1);
                Save(outerList, 1, data.Id);
            });
        }

        public Table GetTable(List<Table> list, string name)
        {
            foreach (var t in list)
            {
                var pre = t.Node.PreviousSibling.PreviousSibling;
                if (pre.Name.Equals("p") && pre.FirstChild != null && pre.FirstChild.FirstChild != null && name.Contains(pre.FirstChild.FirstChild.Value))
                {
                    return t;
                }
            }
            return null;
        }

        public void Save(List<Parameter> parameters, int argType, int interfaceId)
        {
            foreach (var p in parameters)
            {
                Parameter data = DbContext.StockClient.Queryable<Parameter>().First(t => t.IntefaceId.Equals(interfaceId) && t.Name.Equals(p.Name) && t.ArgTtype.Equals(argType));
                if (data == null)
                {
                    data = p;
                    data.IntefaceId = interfaceId;
                    data.ArgTtype = argType;
                    DbContext.StockClient.Insertable(data).ExecuteCommand();
                }
            }
        }

        public List<Parameter> GetParameterFromTable(Table table, int argType)
        {
            List<Parameter> list = new List<Parameter>();
            if (table == null)
            {
                return list;
            }
            List<Tr> rows = table.Node.GetTags<Tr>();
            for (int x = 1; x < rows.Count; x++)
            {
                list.Add(GetParameter(rows[x], argType));
            }
            return list;
        }

        public Parameter GetParameter(Tr tr, int argType)
        {
            List<Td> tds = tr.Node.GetTags<Td>();
            string name = tds[0].text;
            string type = tds[1].text;
            string required = "";
            if (argType == 0)
            {
                required = tds[2].text;
            }
            string description = tds[tds.Count - 1].text;
            return new Parameter
            {
                Name = name,
                Description = description,
                Required = required,
                Type = type,
            };
        }
    }
}
